<?php
/*
 * @Author: 代勇 1031850847@qq.com
 * @Date: 2023-01-30 15:30:09
 * @LastEditors: 代勇 1031850847@qq.com
 * @LastEditTime: 2025-02-06 16:39:49
 * @Description: 常用方法
 */

namespace Daiyong;

class Func {
    public static $baifenTime = 0;
    /**
     * @description: 返回百分比字符串,主要用于百分比提示
     * @param {int} $now 当前数值
     * @param {int} $all 总数值
     * @param {bool} $showtime 是否显示时间
     * @return {string}
     */
    public static function baifen($now, $all, $showtime = true) {
        $str = $now . '/' . $all . '(' . number_format($now / $all * 100, 2) . '%)';
        if ($showtime) {
            if (!self::$baifenTime) {
                self::$baifenTime = time();
            }
            $str .= ' - ' . (time() - self::$baifenTime) . 's';
        }
        return $str . PHP_EOL;
    }

    /**
     * @description: 随机数
     * @param {int} $count 随机数个数
     * @param {string} $string 随机字符串
     * @return {string}
     */
    public static function random($count = 5, $string = '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
        $random = '';
        for ($i = 0; $i < $count; $i++) {
            if (function_exists('mb_strlen')) {
                $scount = mb_strlen($string, 'utf-8');
            } else {
                $scount = strlen($string);
            }
            $rand = mt_rand(0, $scount - 1);
            if (function_exists('mb_strlen')) {
                $random .= mb_substr($string, $rand, 1);
            } else {
                $random .= substr($string, $rand, 1);
            }
        }
        return $random;
    }

    /**
     * @description: 一维数组排序
     * @param {array} $array 一维数组
     * @param {string} $key 需要排序的key
     * @param {string} $sort asc或者desc
     * @return {array} 排序后的数组
     */
    public static function arraySort($array, $key, $sort = 'asc') {
        $sortKey = array();
        foreach ($array as $k => $v) {
            $sortKey[$k] = $v[$key];
        }
        if ($sort == 'asc') {
            asort($sortKey);
        } else {
            arsort($sortKey);
        }
        $data = array();
        foreach ($sortKey as $k => $v) {
            $data[$k] = $array[$k];
        }
        return $data;
    }

    /**
     * @description: 一长串的rsa转换为换行模式的rsa
     * @param {string} $str rsa公钥或者私钥
     * @param {boolen} $type true公钥false私钥
     * @return {string} 换行模式的rsa
     */
    public static function rsa64($str, $type = false) {
        if (!$type) {
            $type = 'PUBLIC';
        } else {
            $type = 'PRIVATE';
        }
        return '-----BEGIN RSA ' . $type . ' KEY-----' . PHP_EOL . wordwrap($str, 64, PHP_EOL, true) . PHP_EOL . '-----END RSA ' . $type . ' KEY-----' . PHP_EOL;
    }
}
